package com.xiaoyuer.yygh.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.xiaoyuer.yygh.cmn.mapper.DictMapper;
import com.xiaoyuer.yygh.model.entity.cmn.Dict;
import com.xiaoyuer.yygh.model.vo.DictEeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

// 有个很重要的点 DictListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去

public class DictListener extends AnalysisEventListener<DictEeVo> {
    private static final Logger LOGGER = LoggerFactory.getLogger(AnalysisEventListener.class);

    private DictMapper dictMapper;

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(dictEeVo));
        //调用方法添加数据库
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo,dict);
        dictMapper.insert(dict);
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        LOGGER.info("所有数据解析完成！");
    }
}
